// #pragma once
#include <chat.h>
#include <widget.h>
#include "ui_chat.h"

Chat::Chat(QWidget *parent)
    : QWidget(parent)
    , connect_to_server(1)
    , chat_ui(new Ui::Chat)
{
    chat_ui->setupUi(this);
}

Chat::Chat(QTcpSocket* skt, QWidget *parent)
    : QWidget(parent)
    , connect_to_server(1)
    , chat_ui(new Ui::Chat)
{
    chat_ui->setupUi(this);
    chat_socket = skt;

    // 建立与服务器的链接，QTcpSocket::readyRead 表示只有 socket 内容变化就触发
    connect(chat_socket, &QTcpSocket::readyRead, this, &Chat::server_info_slot);
}

Chat::~Chat()
{
    delete chat_ui;
}

void Chat::server_info_slot()
{
    QString curTime = QTime::currentTime().toString("[hh:mm:ss] ");
    // QByteArray datas = chat_socket->readAll();

    // 显示接收消息
    chat_ui->socket_textEdit->append(curTime + QString("服务器发来消息:\n    ") + QString(chat_socket->readAll())); // readAll() 返回 QByteArray
    // qDebug() << "服务器错误信息：" << server->errorString();
}

void Chat::on_clear_pushButton_clicked()
{
    chat_ui->textEdit->clear();
}

void Chat::on_send_pushButton_clicked()
{
    QString curTime = QTime::currentTime().toString("[hh:mm:ss] ");
    qDebug() << connect_to_server;
    if (connect_to_server)
    {
        QString current_input = chat_ui->textEdit->toPlainText();
        QByteArray byte_array(current_input.toUtf8().data());
        // byte_array.append(QByteArray a) 方法同上
        chat_socket->write(byte_array);      // 写入到套接字
        chat_socket->waitForBytesWritten();  // 等待数据发送完成

        // 消息框显示记录
        chat_ui->socket_textEdit->append(curTime + "我:\n    " + current_input);
    }
    else // 消息框提示消息未发送
        chat_ui->socket_textEdit->append(curTime + "我:\n    未连接服务器，消息发送失败");

    // 清空输入
    chat_ui->textEdit->clear();
}

QString Chat::get_port()
{
    return port;
}

void Chat::closeEvent(QCloseEvent *ev)
{
    // QMessageBox::information(this, "提示", "退出窗口");
    QString cancel_info("端口断开连接");
    QByteArray cancel_byte_array(cancel_info.toStdString());
    chat_socket->write(cancel_byte_array);  // 写入到套接字
    chat_socket->close();
    Widget* wid = new Widget;
    wid->show();
}
